from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_cors import CORS
import os
from datetime import timedelta

# 初始化扩展
db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()

def create_app(config_name=None):
    app = Flask(__name__)
    
    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/skillc'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 配置JWT
    app.config['JWT_SECRET_KEY'] = 'super-secret'  # 在生产环境中应该使用环境变量
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1)
    app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=30)
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    CORS(app)
    
    # 注册蓝图
    from app.routes.user_routes import user_bp
    from app.routes.food_routes import food_bp
    from app.routes.points_routes import points_bp
    from app.routes.news_routes import news_bp
    from app.routes.comment_routes import comment_bp
    from app.routes.book_routes import book_bp
    from app.routes.bonus_routes import bonus_bp
    from app.routes.order_routes import order_bp
    from app.routes.balance_routes import balance_bp
    from app.routes.club_routes import club_bp
    from app.routes.activity_routes import activity_bp
    from app.routes.radar_routes import radar_bp
    
    app.register_blueprint(user_bp)
    app.register_blueprint(food_bp)
    app.register_blueprint(points_bp)
    app.register_blueprint(news_bp)
    app.register_blueprint(comment_bp)
    app.register_blueprint(book_bp)
    app.register_blueprint(bonus_bp)
    app.register_blueprint(order_bp)
    app.register_blueprint(balance_bp)
    app.register_blueprint(club_bp)
    app.register_blueprint(activity_bp)
    app.register_blueprint(radar_bp)
    
    return app
